﻿namespace BlackHole
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Web.UI.WebControls;
    using BlackHole.DAO;
    using NPOI.HSSF.UserModel;

    public partial class DataImport : System.Web.UI.Page
    {
        private List<ImportRecord> records = new List<ImportRecord>();

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (Uploader.PostedFile.ContentLength != 0)
            {
                try
                {
                    string destDir = Server.MapPath("./Upload/");
                    Uploader.SaveAs(destDir + "up.xls");
                    btnInsert.Enabled = VaildateImportData(destDir + "up.xls");
                }
                catch (Exception)
                {
                    throw;
                }
            }

            panelVaildate.Visible = true;
            ViewState["ImportRecords"] = this.records;
        }

        /// <summary>
        /// 校验数据能否插入
        /// </summary>
        /// <param name="xlsFilePath">数据文件路径</param>
        /// <returns>flag</returns>
        protected bool VaildateImportData(string xlsFilePath)
        {
            bool ret = true;
            int totalCount = 0, errCount = 0;
            List<District> districts = new List<District>();
            List<Owner> owners = new List<Owner>();
            List<Device> devices = new List<Device>();
            List<Fault> faults = new List<Fault>();
            devices = Utility.GetAllDevices();
            districts = Utility.GetAllDistricts();

            try
            {
                // read the xls file
                FileStream fs = new FileStream(xlsFilePath, FileMode.Open, FileAccess.Read);
                HSSFWorkbook workbook = new HSSFWorkbook(fs);

                // get sheet named as 数据导入
                var sheet = workbook.GetSheet("待导入数据");
                for (int i = 1; i <= sheet.LastRowNum; i++)
                {
                    ImportRecord r = new ImportRecord();

                    // convert district id from district name
                    District district = new District();
                    foreach (District d in districts)
                        if (d.DistrictName.Contains(sheet.GetRow(i).GetCell(0).ToString())) district.Id = d.Id;

                    // convert owner id from owner name
                    owners = Utility.GetOwnersByDistrictId(district.Id);
                    foreach (Owner o in owners)
                        if (o.OwnerName.Contains(sheet.GetRow(i).GetCell(1).ToString())) r.OwnerId = o.Id;

                    // convert device id from devicename 
                    foreach (Device d in devices)
                        if (d.DeviceName.Contains(sheet.GetRow(i).GetCell(2).ToString())) r.ProductDeviceId = d.Id;

                    // get product SerialNo and PSamNo and RomVersion
                    r.ProductSerialNO = sheet.GetRow(i).GetCell(3).ToString();
                    r.ProductPsamNO =
                        sheet.GetRow(i).GetCell(4) == null ? string.Empty : sheet.GetRow(i).GetCell(4).ToString();
                    r.ProductRomVersion =
                        sheet.GetRow(i).GetCell(5) == null ? string.Empty : sheet.GetRow(i).GetCell(5).ToString();

                    // get record information
                    // fill faults by device ID
                    faults = Utility.GetFaultsByDeviceId(r.ProductDeviceId);

                    // convert fault id from fault name
                    foreach (Fault f in faults)
                        if (sheet.GetRow(i).GetCell(6) != null)
                        {
                            if (f.FaultName.Contains(sheet.GetRow(i).GetCell(6).ToString())) r.RequestFaultId = f.Id;
                        }

                    foreach (Fault f in faults)
                        if (sheet.GetRow(i).GetCell(6) != null)
                        {
                            if (f.FaultName.Contains(sheet.GetRow(i).GetCell(7).ToString())) r.RealFaultId = f.Id;
                        }

                    r.RepairMethod =
                        sheet.GetRow(i).GetCell(8) == null ? string.Empty : sheet.GetRow(i).GetCell(8).ToString();
                    r.RepairGear =
                        sheet.GetRow(i).GetCell(9) == null ? string.Empty : sheet.GetRow(i).GetCell(9).ToString();

                    // determind is import as record
                    if (r.RequestFaultId != 0 &&
                        r.RealFaultId != 0 &&
                        r.RepairMethod.Length != 0 &&
                        r.RepairGear.Length != 0 &&
                        r.InDate.Length != 0 &&
                        r.OutDate.Length != 0) r.IsRecord = true;

                    // check product import succeed
                    if (Utility.CheckProdcutImport(ref r))
                    {
                        r.IsImportable = true;
                    }
                    else
                    {
                        // check record import succeed
                        r.IsImportable = false;
                        errCount++;
                    }

                    if (r.ProductSerialNO.Length > 0)
                    {
                        records.Add(r);
                        totalCount++;
                    }
                }
            }
            catch (NPOI.OldFileFormatException)
            {
                throw;
            }
            catch (Exception)
            {
            }

            lblStats.Text = "总计： " + totalCount.ToString() + "个,     冲突: " + errCount.ToString() + "个";
            dataProducts.DataSource = records;
            dataProducts.DataBind();

            return ret;
        }

        protected void chkForce_CheckedChanged(object sender, EventArgs e)
        {
            btnInsert.Enabled = chkForce.Checked;
        }

        protected void btnInsert_Click(object sender, EventArgs e)
        {
            bool ret;
            int count = 0;
            this.records = (List<ImportRecord>)ViewState["ImportRecords"];
            List<ImportRecord> errorlist = new List<ImportRecord>();
            foreach (ImportRecord r in this.records)
            {
                if (r.IsImportable == false) continue;

                // 修完的直接出库 
                if (r.IsRecord)
                {
                    ret = Utility.ProductRepair(r.ProductId, r.RequestFaultId, r.RealFaultId, r.RepairMethod, r.RepairGear);
                    Utility.ProductCheckOut(r.ProductId);
                }
                else
                {
                    ret = Utility.ProductAddNew(r.ProductDeviceId, r.OwnerId, r.ProductSerialNO, r.ProductPsamNO, r.ProductRomVersion);
                }

                if (ret)
                {
                    count++;
                }
                else
                {
                    errorlist.Add(r);
                }
            }

            lblStats.Text = "导入完成 共 " + count.ToString();
            chkForce.Visible = false;
            btnInsert.Visible = false;

            dataProducts.DataSource = errorlist;
            dataProducts.DataBind();
        }
    }
}